package org.example.myleet.learn.web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServerTest {

    static class DialogHandler implements Runnable {

        private Socket socket;

        private boolean done;

        public DialogHandler(Socket socket) {
            this.socket = socket;
            this.done = false;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                Scanner scanner = new Scanner(socket.getInputStream(), "UTF-8");
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
                writer.println("Hello! Enter 'BYE' to exit dialog.");
                while (!done) {
                    String line = scanner.nextLine();
                    writer.printf("Echo: %s\n", line);
                    if ("BYE".equals(line.trim())) {
                        done = true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8189)) {
            int i = 1;
            for (;;) {
                Socket incoming = serverSocket.accept();
                System.out.println("Spawning " + i);
                Thread t = new Thread(new DialogHandler(incoming));
                t.start();
                ++i;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
